package com.changgou.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.Searchservice;
import org.apache.lucene.queryparser.xml.builders.BooleanQueryBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static sun.security.krb5.internal.crypto.Nonce.value;

@Service
public class SearchServiceImpl implements Searchservice {


    @Autowired
    private ElasticsearchTemplate esTemplate;


    @Override
    public Map search(Map<String, String> map) {
        // 要返回的map
        Map<String, Object> resultMap = new HashMap<>();

        // 构建查询
        if (map != null) {
            // 开启查询
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 名字查询
            if (!StringUtils.isEmpty(map.get("keywords"))) {
                boolQuery.must(QueryBuilders.matchQuery("name", map.get("keywords")).operator(Operator.AND));
            }

            // 品牌查询
            if (!StringUtils.isEmpty(map.get("brand"))) {
                boolQuery.filter(QueryBuilders.termQuery("brandName", map.get("brand")));

            }


            // 价格区间查询
            if (!StringUtils.isEmpty(map.get("price"))) {

                String[] prices = map.get("price").split("-");

                if (prices.length == 2) {
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));

                }

                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));


            }


            // 按照规格进行过滤查询
            for (String key : map.keySet()) {
                if (key.startsWith("spec_")) {
                    String value = map.get(key).replace("%2B", "+");
                    boolQuery.filter(QueryBuilders.termQuery(("specMap." + key.substring(5) + ".keyword"), value));


                }
            }


            // 开启分页查询
            String pageNum = map.get("pageNum");
            String pageSize = map.get("pageSize");
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));


            nativeSearchQueryBuilder.withQuery(boolQuery);


            // 按照品牌进行聚合查询
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            // 按照规格进行聚合查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));


            // 按照相关字段进行排序
            if (!StringUtils.isEmpty(map.get("sortField")) && !StringUtils.isEmpty(map.get("sortRule"))) {

                if ("ASC".equals(map.get("sortRule"))) {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(map.get("sortField")).order(SortOrder.ASC));

                } else {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(map.get("sortField")).order(SortOrder.DESC));

                }
            }


            // 设置高亮
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")
                    .preTags("<span style='color:red'>")
                    .postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);


            // 三个参数
            /**
             * 第一个参数: 条件构建对象
             * 第二个参数: 查询操作实体类
             * 第三个参数: 查询结果操作对象
             */
            AggregatedPage<SkuInfo> skuInfos = esTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {

                    // 查询结果操作
                    List<T> list = new ArrayList<>();

                    // 获取查询命中的结果集
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            String sourceAsString = hit.getSourceAsString();
                            SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);

                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0) {
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }


                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });


            // 封装查询结果
            resultMap.put("total", skuInfos.getTotalElements());
            resultMap.put("totalPages", skuInfos.getTotalPages());
            resultMap.put("rows", skuInfos.getContent());


            // 封装品牌的分组结果
            StringTerms brandTerms = (StringTerms) skuInfos.getAggregation(skuBrand);
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);


            // 封装规格的分组结果
            StringTerms specTerms = (StringTerms) skuInfos.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", this.formartSpec(specList));


            // 封装当前页
            resultMap.put("pageNum", pageNum);


            return resultMap;
        }


        return null;
    }


    public Map<String, Set<String>> formartSpec(List<String> specList) {

        Map<String, Set<String>> resultMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(specList)) {
            for (String s : specList) {
                Map<String,String> map = JSON.parseObject(s, Map.class);
                for (String specKey : map.keySet()) {
                    Set<String> specSet = resultMap.get(specKey);

                    if (specSet == null){
                        specSet = new HashSet<String>();
                    }

                    specSet.add(map.get(specKey));

                    resultMap.put(specKey,specSet);

                }

            }
        }

        return resultMap;
    }


}
